// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()


const axios = require('axios');
const cheerio = require('cheerio');
const doubanbook = require('doubanbook');


async function getDoubanSearch(isbn){
    let searchUrl = `https://book.douban.com/subject_search?search_text=` + isbn;

    const htmlSource = await axios.get(searchUrl);
    let reg = /window\.__DATA__ = "(.*)"/;
    
    if (reg.test(htmlSource.data)){
        return doubanbook(RegExp.$1)[0];
        
    }else{
        return {}
    }

}

async function getDouban(isbn){
    let searchData = await getDoubanSearch(isbn);
    let detailPage = await axios.get(searchData.url);
    
    const $ = cheerio.load(detailPage.data);

    let bookInfo = $('#info').text().split(/\n/).map(v=>v.trim()).filter(v=>v);
    

    let _data = {
        create_time:Date.now(),
        rating:searchData.rating,
        title:searchData.title,
        cover_url:searchData.cover_url,
        author:bookInfo[1],
        publisher:bookInfo[2].split(':')[1],
        publishYear:bookInfo[3].split(':')[1],
        pages:bookInfo[4].split(':')[1],
        price:bookInfo[5].split(':')[1],
        isbn:bookInfo[bookInfo.length-1].split(':')[1],
        desc: $('#link-report .intro').text(),

    };

    let tags = [];
    $('#db-tags-section a.tag').each((i, v)=>{
        tags.push($(v).text())
    })
    _data.tags = tags;


    return _data;
    
}








// 云函数入口函数
exports.main = async (event, context) => {
    let { isbn } = event;

    if(isbn){
        return getDouban(isbn);
    }else{
        return {
            code:-1,
            message:'请扫描正确的图书'
        }
    }
}